package com.sgb.contract.view.ui.list;

import com.alibaba.android.arouter.launcher.ARouter;
import com.sgb.contract.api.AbstractCallBack;
import com.sgb.contract.api.ContractNet;
import com.sgb.contract.base.viewmodel.BaseViewModel;
import com.sgb.contract.model.ContractApprovalStatusBean;
import com.sgb.contract.model.ContractKeyValueBean;
import com.sgb.contract.model.ContractListSearchBean;
import com.sgb.contract.utils.ArouterConfigs;
import com.swgk.core.base.model.entity.BaseEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.lifecycle.MutableLiveData;

/**
 * 合同列表
 *
 * @author cyj
 */
public class ContractViewModel extends BaseViewModel {

    private int page = 1;
    public ContractListAdapter adapter;
    private ContractListSearchBean.ContractListInfo currentBean = null;
    /**
     * tab 选项卡选中状态
     */
    public ObservableInt selectTab = new ObservableInt(0);
    /**
     * tab 选项卡选中状态
     */
    public ObservableBoolean selectTab5 = new ObservableBoolean(false);
    /**
     * tab 选项卡选中状态
     */
    public ObservableBoolean selectTab6 = new ObservableBoolean(false);
    /**
     * tab 审批状态-选项卡选中状态
     */
    public ObservableBoolean selectTab7 = new ObservableBoolean(false);
    /**
     * 是否显示修改合同的弹窗布局
     */
    public MutableLiveData<Boolean> showRejectContractPop = new MutableLiveData<>();

    /**
     * vm中全局的查询合同的条件
     */
    private final ObservableField<Map<String, Object>> selectContractListMap = new ObservableField<>(new HashMap<>());
    /**
     * pop弹窗数据更新
     */
    public MutableLiveData<List<ContractKeyValueBean>> contractTypeList = new MutableLiveData<>();
    public MutableLiveData<List<ContractKeyValueBean>> contractStateList = new MutableLiveData<>();
    public MutableLiveData<List<ContractKeyValueBean>> approvalStateList = new MutableLiveData<>();
    /**
     * 列表数据更新
     */
    public MutableLiveData<Boolean> hasNoContractListData = new MutableLiveData<>();

    public ContractViewModel() {
        adapter = new ContractListAdapter(application.getApplicationContext());
    }

    /**
     * 获取合同列表数据
     */
    public void getContractList(boolean isLoadMore) {

        Map<String, Object> map = selectContractListMap.get();
        map.put("page", page = isLoadMore ? ++page : 1);
        map.put("limit", 20);

        showLoading(true);
        ContractNet.getInstance().getContractApi().contractListSearch(map).enqueue(new AbstractCallBack<BaseEntity<ContractListSearchBean>>() {
            @Override
            public void onSuccess(BaseEntity<ContractListSearchBean> data) {

                // int i = true ? View.GONE : true ? View.GONE : true ? View.VISIBLE : View.GONE;
               // int i = true ? View.GONE : true ? View.GONE : true ? View.VISIBLE : !true ? View.VISIBLE : View.GONE;
                if (1 == page && data.getData().list.size() <= 0) {
                    hasNoContractListData.postValue(true);
                }
                if (!isLoadMore) {
                    adapter.setDatas(data.getData().list);
                } else {
                    adapter.addDatas(data.getData().list);
                    adapter.setNoMore(data.getData().list.size() <= 0);
                }
            }

            @Override
            public void onFinally() {
                super.onFinally();
                adapter.refreshComplete();
                adapter.loadMoreComplete();
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 根据合同分类搜索合同
     *
     * @param type 合同分类
     */
    public void getContractListForType(String type) {
        if ("-1".equals(type)) {
            // 全部
            selectContractListMap.get().remove("type");
            getContractList(false);
        } else {
            Map<String, Object> map = selectContractListMap.get();
            map.put("page", 1);
            map.put("limit", 20);
            map.put("type", type);
            getContractListForBean(map);
        }
    }

    /**
     * 根据合同状态搜索合同
     *
     * @param status 合同状态
     */
    public void getContractListForStatus(String status) {
        if ("-1".equals(status)) {
            // 全部
            selectContractListMap.get().remove("status");
            getContractList(false);
        } else {
            Map<String, Object> map = selectContractListMap.get();
            map.put("page", 1);
            map.put("limit", 20);
            map.put("status", status);
            getContractListForBean(map);
        }
    }

    /**
     * 根据合同审批状态搜索合同
     *
     * @param approval 审批状态
     */
    public void getContractListForApproval(String approval) {
        if ("-1".equals(approval)) {
            // 全部
            Objects.requireNonNull(selectContractListMap.get()).remove("auditStatus");
            getContractList(false);
        } else {
            Map<String, Object> map = selectContractListMap.get();
            map.put("page", 1);
            map.put("limit", 20);
            map.put("auditStatus", approval);
            getContractListForBean(map);
        }
    }

    /**
     * 根据合同名称搜索合同
     *
     * @param title 合同名称
     */
    public void getContractListForTitle(String title) {
        Map<String, Object> map = selectContractListMap.get();
        map.put("page", 1);
        map.put("limit", 20);
        map.put("title", title);
        getContractListForBean(map);
    }

    /**
     * 查询合同列表
     *
     * @param map
     */
    public void getContractListForBean(Map<String, Object> map) {
        showLoading(true);
        ContractNet.getInstance().getContractApi().contractListSearch(map).enqueue(new AbstractCallBack<BaseEntity<ContractListSearchBean>>() {
            @Override
            public void onSuccess(BaseEntity<ContractListSearchBean> data) {
                if (null != data.getData().list && data.getData().list.size() <= 0) {
                    hasNoContractListData.postValue(true);
                }
                adapter.setDatas(data.getData().list);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 获取合同分类pop弹窗数据集
     */
    public void getContractType() {
        if (null != contractTypeList.getValue() && contractTypeList.getValue().size() > 0) {
            return;
        }
        ContractNet.getInstance().getContractApi().getContractType().enqueue(new AbstractCallBack<BaseEntity<List<ContractKeyValueBean>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ContractKeyValueBean>> data) {
                contractTypeList.postValue(data.getData());
            }
        });
    }

    /**
     * 获取合同状态pop弹窗数据集
     */
    public void getContractStatus() {
        if (null != contractStateList.getValue() && contractStateList.getValue().size() > 0) {
            return;
        }
        ContractNet.getInstance().getContractApi().getContractStatus().enqueue(new AbstractCallBack<BaseEntity<List<ContractKeyValueBean>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ContractKeyValueBean>> data) {
                contractStateList.postValue(data.getData());
            }
        });
    }

    /**
     * 获取合同审批状态pop弹窗数据集
     */
    public void getContractApprovalStatus() {
        List<ContractKeyValueBean> contractApprovalList = new ArrayList<>();
        ContractKeyValueBean contractApprovalBean1 = new ContractKeyValueBean();
        contractApprovalBean1.key = "1";
        contractApprovalBean1.value = "审批中";
        contractApprovalList.add(contractApprovalBean1);

        ContractKeyValueBean contractApprovalBean2 = new ContractKeyValueBean();
        contractApprovalBean2.key = "2";
        contractApprovalBean2.value = "已通过";
        contractApprovalList.add(contractApprovalBean2);

        ContractKeyValueBean contractApprovalBean3 = new ContractKeyValueBean();
        contractApprovalBean3.key = "3";
        contractApprovalBean3.value = "已拒绝";
        contractApprovalList.add(contractApprovalBean3);
        approvalStateList.setValue(contractApprovalList);
    }

    /**
     * 校验合同状态
     */
    public void checkStatusByNowStatus(String tag, ContractListSearchBean.ContractListInfo bean) {
        if (null == bean.localUrl) {
            showDialog("", "当前合同暂无内容\n请在电脑端编辑后再操作！");
            return;
        }
        if (adapter.TAG[2].equals(tag)) {
            // 查看合同
            ARouter.getInstance().build(ArouterConfigs.AR_SIGN_CONTRACT)
                    .withBoolean("isShowOperationLayout", false)
                    .withString("contractId", String.valueOf(bean.id))
                    .navigation();
        } else {
            showLoading();
            ContractNet.getInstance().getContractApi().checkStatusByNowStatus(bean.no, String.valueOf(bean.status), bean.appSignStatus, bean.appSignTag, bean.appAuditStatus)
                    .enqueue(new AbstractCallBack<BaseEntity<Boolean>>() {
                        @Override
                        public void onSuccess(BaseEntity<Boolean> data) {
                            // 操作合同
                            operationContract(tag, bean);
                        }

                        @Override
                        public void onBusinessFailure(BaseEntity entity) {
                            showDialog("checkStatusByNowStatus", entity.getMsg());
                        }
                    });
        }
    }

    /**
     * 操作合同，比如：发送合同，退回合同，查看合同等等
     *
     * @param bean
     */
    public void operationContract(String tag, ContractListSearchBean.ContractListInfo bean) {
        currentBean = bean;
        if (adapter.TAG[0].equals(tag)) {
            // 退回合同
            if (null == bean.localUrl) {
                showDialog("", "当前合同暂无内容\n请在电脑端编辑后再操作！");
                return;
            }
            showDialog("discardContract", "退回合同后不可恢复\n还要继续吗？", "取消", "退回");
        } else if (adapter.TAG[1].equals(tag)) {
            // 发送合同
            if (null == bean.localUrl) {
                showDialog("", "当前合同暂无内容\n请在电脑端编辑后再操作！");
                return;
            }
            sendContract(bean);
        } else if (adapter.TAG[2].equals(tag)) {
//            if(null == bean.localUrl) {
//                showDialog("", "当前合同暂无内容\n请在电脑端编辑后再操作！");
//                return;
//            }
//            // 查看合同
//            ARouter.getInstance().build(ArouterConfigs.AR_SIGN_CONTRACT)
//                    .withBoolean("isShowOperationLayout", false)
//                    .withString("contractId", String.valueOf(bean.id))
//                    .navigation();
        } else if (adapter.TAG[3].equals(tag)) {
            // 签署合同
            ARouter.getInstance().build(ArouterConfigs.AR_SIGN_CONTRACT)
                    .withString("contractId", String.valueOf(bean.id))
                    .navigation();
        } else if (adapter.TAG[4].equals(tag)) {
            // 修改合同
            // TODO: 2021/12/3 0003
            findAuditStatus(bean.id, "signContract", bean.appAuditStatus);
        }
    }

    /**
     * 发送合同
     *
     * @param bean
     */
    public void sendContract(ContractListSearchBean.ContractListInfo bean) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", bean.id);
        map.put("contractNo", bean.no);
        map.put("currentStatus", String.valueOf(bean.status));
        ContractNet.getInstance().getContractApi().sendContract(map).enqueue(new AbstractCallBack<BaseEntity<Object>>() {
            @Override
            public void onSuccess(BaseEntity<Object> data) {
                getContractList(false);
            }

            @Override
            public void onBusinessFailure(BaseEntity entity) {
                showDialog("", entity.getMsg());
            }
        });
    }

    /**
     * 退回合同
     */
    public void discardContract() {
        if (null == currentBean) {
            return;
        }
        ContractNet.getInstance().getContractApi().checkStatusByNowStatus(currentBean.no, String.valueOf(currentBean.status), currentBean.appSignStatus, currentBean.appSignTag, currentBean.appAuditStatus)
                .enqueue(new AbstractCallBack<BaseEntity<Boolean>>() {
                    @Override
                    public void onSuccess(BaseEntity<Boolean> data) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("contractId", currentBean.id);
                        map.put("contractNo", currentBean.no);
                        map.put("localUrl", currentBean.localUrl);
                        map.put("currentStatus", String.valueOf(currentBean.status));
                        ContractNet.getInstance().getContractApi().discardContract(map).enqueue(new AbstractCallBack<BaseEntity<Object>>() {
                            @Override
                            public void onSuccess(BaseEntity<Object> data) {
                                getContractList(false);
                            }

                            @Override
                            public void onBusinessFailure(BaseEntity entity) {
                                showDialog("", entity.getMsg());
                            }
                        });
                    }

                    @Override
                    public void onBusinessFailure(BaseEntity entity) {
                        showDialog("checkStatusByNowStatus", entity.getMsg());
                    }
                });
    }

    /**
     * 修改合同-确认
     */
    public void rejectContractSure(String content) {
        if (null == currentBean) {
            return;
        }
        ContractNet.getInstance().getContractApi().checkStatusByNowStatus(currentBean.no, String.valueOf(currentBean.status), currentBean.appSignStatus, currentBean.appSignTag, currentBean.appAuditStatus)
                .enqueue(new AbstractCallBack<BaseEntity<Boolean>>() {
                    @Override
                    public void onSuccess(BaseEntity<Boolean> data) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("companyNo", currentBean.companyNo);
                        map.put("contractNo", currentBean.no);
                        map.put("currentStatus", currentBean.status);
                        map.put("id", currentBean.id);
                        map.put("remark", null == content ? "" : content);
                        ContractNet.getInstance().getContractApi().rejectContract(map).enqueue(new AbstractCallBack<BaseEntity<Object>>() {
                            @Override
                            public void onSuccess(BaseEntity<Object> data) {
                                getContractList(false);
                            }
                        });
                    }

                    @Override
                    public void onBusinessFailure(BaseEntity entity) {
                        showDialog("checkStatusByNowStatus", entity.getMsg());
                    }
                });
    }

    /**
     * 查询合同的审批状态
     *
     * @param id        合同id
     * @param auditType auditType 审批类型：发送审批 sendContract 签署审批 signContract
     */
    private void findAuditStatus(long id, String auditType, int auditStatus) {
        ContractNet.getInstance().getContractApi().findAuditStatus(id, auditType).enqueue(new AbstractCallBack<BaseEntity<ContractApprovalStatusBean>>() {
            @Override
            public void onSuccess(BaseEntity<ContractApprovalStatusBean> data) {
                if (data.getData().auditStatus == auditStatus) {
                    // showRejectContractPop.setValue(true);
                    // TODO: 2021/12/3 0003
                    showDialog("", "请前往电脑端进行合同编辑！");
                } else {
                    showDialog("checkApprovalOpenAudit", data.getMsg());
                }
            }
        });
    }
}
